<?php
Authenticate::requireAccounting();

$payments = array();

$db = Db::getInstance();
$query = "SELECT * FROM Payment WHERE status=0";
$mode = isset($_GET['mode'])? $_GET['mode']: 'daily';
if($mode=='weekly'){
	$query .= " AND (YEARWEEK(createTime) = YEARWEEK(CURRENT_DATE))";
}
else if($mode=='monthly'){
	$query .= " AND (MONTH(createTime) = MONTH(CURRENT_DATE))";
}
else if($mode=='yearly'){
	$query .= " AND (YEAR(createTime) = YEAR(CURRENT_DATE))";
}
else {
	$query .= " AND (DATE(createTime) = DATE(CURRENT_DATE))";
}
$query .= " ORDER BY createTime DESC";
$result = $db->query($query);

if(!$result){ echo $db->error; }

$queryInvoice = "SELECT * FROM PaymentInvoice JOIN Invoice ON PaymentInvoice.invoiceId=Invoice.id WHERE paymentId='%s'";
while ($row = $result->fetch_assoc()){
	$result2 = $db->query(sprintf($queryInvoice, $row['id']));
	if(!$result2){ echo $db->error; }
	$invoices = array();
	while($row2 = $result2->fetch_assoc()){
		$row2['package'] = Package::instance()->getOne($row2['packageId']);
		$invoices[] = $row2;
	}
	$row['invoices'] = $invoices;
	$row['account'] = Account::instance()->getOne($row['accountId']);
	$payments[] = $row;
}

View::display('accounting/payment', array('payments'=> $payments));